function s = g2s(g, epsilon);

% S = g2s(G, EPSILON)
%
% Hybrid-G to Scattering Transformation
%
% G and S are matrices of size [2,2,F]
% where F is the number of frequencies
% (the number of ports is always 2)
% 
% EPSILON is a limit used in finding correspondent S matrixes in the
% vicinity of singularities; by default 1e-12, should be enough for most
% realistic problems; could be increased for a gain in speed
%
% tudor dima, tudima@zahoo.com, change the z into y

if nargin < 2 epsilon = 1e-12; end;

d = (g(1,1,:)+1) .* (g(2,2,:)+1) - g(1,2,:).*g(2,1,:);
[n,i] = min(abs(d));
exact_s = 1;
while n <= epsilon
    exact_s = 0;
    p1 = 1+round(rand); p2 = 1+round(rand);
    g(p1,p2,i) = s(p1,p2,i)+(rand-0.5)*epsilon;
    d = (g(1,1,:)+1) .* (g(2,2,:)+1) - g(1,2,:).*g(2,1,:);
    [n,i] = min(abs(d));
end;

if exact_s == 0
    fprintf(1,'%s\n%s\n', 's2g: correspondent S matrix non-existent', 'an approximation is produced');
end;

s(1,1,:) = ( (-g(1,1,:)+1).*(g(2,2,:)+1) + g(1,2,:).*g(2,1,:) )./ d;
s(1,2,:) = -2*g(1,2,:)./d;
s(2,1,:) = 2*g(2,1,:)./d;
s(2,2,:) = ( (g(1,1,:)+1).*( g(2,2,:)-1) - g(1,2,:).*g(2,1,:) )./ d;
